package com.jt.auth.service.impl;

import com.jt.auth.service.RemoteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserDetailsService接口的实现类负责:
 * 1)通过查询内存获取用户信息 (默认)
 * 2)通过数据库获取用户信息
 * 3)通过Feign接口调用远端Service获取用户信息 (本次选择)
 */
@Service
public class UserDetailsServiceImpl
        implements UserDetailsService {
    @Autowired
    private RemoteUserService remoteUserService;
    /**
     * 此方法在执行登录操作时,由底层自动调用,可以在
     * 此方法中通过用户名查询用户信息
     * @param username
     * @return 用于认证的用户详情信息对象
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //1.基于用户名获取远端用户基本信息
        com.jt.auth.pojo.User user =
          remoteUserService.selectUserByUsername(username);
        if(user==null)
            throw new UsernameNotFoundException("user is not exits");
        //2.基于用户id获取远端用户权限信息
        List<String> permissions =
                remoteUserService.selectUserPermissions(user.getId());
        System.out.println("permissions="+permissions);
        //3.封装结果并返回(交给认证对象-AuthenticationManager,完成用户身份认证)
        return new User(username,//登录用户名
                user.getPassword(),//数据库已加密的密码
                AuthorityUtils.createAuthorityList(//将用户权限转换为方法需要的类型
                        permissions.toArray(new String[]{})));
    }
    //说明:这个方法我们只负责写,不负责调用,这个方法默认就在一个调用链.
}
